package com.ifinc.common.web.controller;

import com.ifinc.common.example.UserController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;


public class CentralControler {

    static final Logger log = LoggerFactory.getLogger(CentralControler.class);

    ResultHandler resultHandler = new ResultHandler();

    HttpTransform httpTransform = new HttpTransform();

    Map<String, Action> actionMap = new HashMap<String, Action>();

    public String execute(HttpServletRequest req, HttpServletResponse resp, String command) {
        //提取httpHeader
        Map<String, String> header = httpTransform.makeHeaderParam(req);
        //提取请求参数
        Map<String, String> reqParam = httpTransform.makeParamMap(req);
        HttpSession session = req.getSession();
        //将session中数据转化成Map的的数据
        SessionMap<String, Object> sessionMap = httpTransform.transformSession(session);

        //查询业务action
        Action action = findAction(command);
        try {
            //执行校验方法
            action.validate(header, reqParam, sessionMap);

            Map<String, Object> actionResult = new LinkedHashMap<String, Object>();
            //执行业务处理方法
            String exeResult = action.execute(header, reqParam, sessionMap,actionResult);
            //将结果中的的数据放到request的attributes中
            httpTransform.putMap2ReqAttr(actionResult, req);
            //返回结果
            return exeResult;
        } catch (Exception e) {
            return resultHandler.handlerException(req, action, reqParam, sessionMap, e);
        } finally {
            //将sessionMap中的数据同步到session中
            httpTransform.putValueToSession(session, sessionMap);
        }
    }

    private Action findAction(String command) {
        Action userController = actionMap.get(command);
        if (userController == null) {
            userController = new UserController();
            actionMap.put("user", userController);
        }
        return userController;
    }
}
